<template>
	<view class="article-detail-container">
		<!-- 自定义导航栏 -->
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<uni-icons type="spinner-cycle" size="40" color="#1989fa"></uni-icons>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 错误提示 -->
		<view v-else-if="error" class="error-container">
			<uni-icons type="close-circle" size="40" color="#ee0a24"></uni-icons>
			<text class="error-text">{{ error }}</text>
			<button @click="fetchArticleDetail" class="retry-btn">重试</button>
		</view>
		
		<!-- 文章详情卡片 -->
		<view v-else-if="article" class="article-card">
			<!-- 文章标题 -->
			<view class="article-title">{{ article.title || '无标题' }}</view>
			
			<!-- 作者和日期信息 -->
			<view class="article-meta">
				<text class="author-name">{{ article.author?.username || '未知作者' }}</text>
				<text class="meta-dot">•</text>
				<text class="publish-date">{{ formatDate(article.createdAt || article.publishTime) }}</text>
			</view>
			
			<!-- 标签 -->
			<view class="article-tags" v-if="article.categories && article.categories.length > 0">
				<view 
					v-for="(tag, index) in article.categories" 
					:key="index" 
					class="tag-item"
				>
					{{ tag }}
				</view>
			</view>
			
			<!-- 封面图片 -->
			<view class="article-cover" v-if="article.coverImage">
				<image 
					:src="article.coverImage" 
					mode="aspectFill"
					class="cover-image"
				></image>
			</view>
			
			<!-- 文章内容 -->
			<view class="article-content">
				<rich-text :nodes="article.content"></rich-text>
			</view>
			
			<!-- 互动操作栏 -->
			<view class="article-actions">
				<view class="action-left">
					<view class="action-btn" @click="toggleLike">
						<uni-icons 
							type="chatbubble" 
							size="22" 
							color="#909399"
						></uni-icons>
						<text class="action-text">{{ comments.length }}</text>
					</view>
				</view>
				<view class="action-right">
					<view class="action-btn" @click="handleShare">
						<uni-icons type="redo" size="22" color="#909399"></uni-icons>
					</view>
					<view class="action-btn" @click="toggleFavorite">
						<uni-icons 
							type="star" 
							size="22" 
							:color="article.isFavorited ? '#FFD700' : '#909399'"
						></uni-icons>
					</view>
					<view class="action-btn" @click="toggleLike">
						<uni-icons 
							type="hand-thumbsup" 
							size="22" 
							:color="article.isLiked ? '#1890ff' : '#909399'"
						></uni-icons>
					</view>
				</view>
			</view>
			
			<!-- 评论区域 -->
			<view class="comments-section">
				<view class="comments-header">
					<text class="comments-title">评论</text>
					<text class="comments-count">({{ comments.length }})</text>
				</view>
				
				<!-- 评论列表 -->
				<view class="comment-list">
					<view v-if="comments.length === 0" class="empty-comment">
						<text>暂无评论</text>
					</view>
					<view v-else v-for="comment in comments" :key="comment.commentId" class="comment-item">
						<view class="comment-avatar">
							<image :src="comment.user?.avatar || '/static/logo.png'" mode="aspectFill"></image>
						</view>
						<view class="comment-body">
							<view class="comment-user-info">
								<text class="comment-username">{{ comment.user?.username || '匿名用户' }}</text>
								<text class="comment-time">{{ formatDate(comment.createdAt) }}</text>
							</view>
							<text class="comment-text">{{ comment.content }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部评论输入框 -->
		<view class="comment-input-bar">
			<input 
				v-model="commentText" 
				class="comment-input" 
				placeholder="写下你的评论..." 
				:adjust-position="true"
			/>
			<button class="send-btn" @click="submitComment" :disabled="!commentText.trim()">
				<uni-icons type="paperplane" size="20" color="#ffffff"></uni-icons>
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { articleApi, commentApi } from '../../common/api/index.js'

// 响应式数据
const article = ref(null)
const comments = ref([])
const loading = ref(false)
const error = ref('')
const commentText = ref('')
const articleId = ref('')

// 格式化日期
const formatDate = (dateString) => {
	if (!dateString) return '未知时间'
	const date = new Date(dateString)
	const now = new Date()
	const diff = now - date
	
	// 小于1分钟
	if (diff < 60 * 1000) {
		return '刚刚'
	}
	// 小于1小时
	else if (diff < 60 * 60 * 1000) {
		return `${Math.floor(diff / (60 * 1000))}分钟前`
	}
	// 小于24小时
	else if (diff < 24 * 60 * 60 * 1000) {
		return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
	}
	// 小于7天
	else if (diff < 7 * 24 * 60 * 60 * 1000) {
		return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
	}
	// 超过7天显示具体日期
	else {
		return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
	}
}

// 获取文章详情
const fetchArticleDetail = async () => {
	if (!articleId.value) {
		error.value = '缺少文章ID'
		return
	}
	
	loading.value = true
	error.value = ''
	
	try {
		const response = await articleApi.getArticleDetail(articleId.value)
		
		if (response.status === 'success' && response.data) {
			article.value = response.data
			// 获取评论列表
			await fetchComments()
		} else {
			error.value = response.message || '获取文章详情失败'
		}
	} catch (err) {
		console.error('获取文章详情失败:', err)
		error.value = '网络错误，请稍后重试'
	} finally {
		loading.value = false
	}
}

// 获取评论列表
const fetchComments = async () => {
	try {
		const response = await commentApi.getComments({
			articleId: articleId.value,
			page: 1,
			pageSize: 100
		})
		
		if (response.status === 'success' && response.data) {
			comments.value = Array.isArray(response.data.items) ? response.data.items : []
		}
	} catch (err) {
		console.error('获取评论列表失败:', err)
	}
}

// 切换点赞状态
const toggleLike = async () => {
	// 检查是否已登录
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		uni.navigateTo({ url: '/pages/login/login' })
		return
	}
	
	const originalLiked = article.value.isLiked
	
	try {
		let response
		if (originalLiked) {
			response = await articleApi.cancelLike(articleId.value)
		} else {
			response = await articleApi.likeArticle(articleId.value)
		}
		
		if (response.status === 'success' && response.data) {
			// 使用后端返回的数据更新状态
			article.value.isLiked = response.data.isLiked
			article.value.likeCount = response.data.likeCount
			
			uni.showToast({
				title: originalLiked ? '已取消点赞' : '点赞成功',
				icon: 'success',
				duration: 1000
			})
		} else {
			uni.showToast({
				title: response.message || '操作失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('点赞操作失败:', err)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
	}
}

// 切换收藏状态
const toggleFavorite = async () => {
	// 检查是否已登录
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		uni.navigateTo({ url: '/pages/login/login' })
		return
	}
	
	const originalFavorited = article.value.isFavorited
	
	try {
		let response
		if (originalFavorited) {
			response = await articleApi.cancelFavorite(articleId.value)
		} else {
			response = await articleApi.favoriteArticle(articleId.value)
		}
		
		if (response.status === 'success' && response.data) {
			// 使用后端返回的数据更新状态
			article.value.isFavorited = response.data.isFavorited
			article.value.favoriteCount = response.data.favoriteCount
			
			uni.showToast({
				title: originalFavorited ? '已取消收藏' : '收藏成功',
				icon: 'success',
				duration: 1000
			})
		} else {
			uni.showToast({
				title: response.message || '操作失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('收藏操作失败:', err)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
	}
}

// 分享功能
const handleShare = () => {
	uni.showToast({
		title: '分享功能开发中',
		icon: 'none'
	})
}

// 提交评论
const submitComment = async () => {
	// 检查是否已登录
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		uni.navigateTo({ url: '/pages/login/login' })
		return
	}
	
	if (!commentText.value.trim()) {
		uni.showToast({
			title: '请输入评论内容',
			icon: 'none'
		})
		return
	}
	
	try {
		const response = await commentApi.addComment({
			articleId: articleId.value,
			content: commentText.value.trim()
		})
		
		if (response.status === 'success') {
			uni.showToast({
				title: '评论成功',
				icon: 'success'
			})
			commentText.value = ''
			// 重新获取评论列表
			await fetchComments()
			// 更新文章评论数
			if (article.value) {
				article.value.commentCount = (article.value.commentCount || 0) + 1
			}
		} else {
			uni.showToast({
				title: response.message || '评论失败',
				icon: 'none'
			})
		}
	} catch (err) {
		console.error('提交评论失败:', err)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
	}
}

// 输入框获得焦点
const onInputFocus = () => {
	// 可以在这里处理一些焦点逻辑
}

// 输入框失去焦点
const onInputBlur = () => {
	// 可以在这里处理一些失焦逻辑
}

// 页面加载时获取文章ID
onLoad((options) => {
	if (options.id) {
		articleId.value = options.id
		fetchArticleDetail()
	} else {
		error.value = '缺少文章ID参数'
	}
})
</script>

<style lang="scss" scoped>
.article-detail-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding-bottom: 140rpx;
	
	// 加载和错误状态
	.loading-container,
	.error-container {
		padding: 200rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.loading-text,
		.error-text {
			margin-top: 30rpx;
			font-size: 28rpx;
			color: #999;
		}
	}
	
	.error-container {
		.retry-btn {
			margin-top: 40rpx;
			padding: 20rpx 60rpx;
			background-color: #1890ff;
			color: #ffffff;
			border-radius: 50rpx;
			font-size: 28rpx;
		}
	}
	
	// 文章卡片
	.article-card {
		background-color: #ffffff;
		margin: 20rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
		
		// 文章标题
		.article-title {
			padding: 40rpx 30rpx 20rpx;
			font-size: 40rpx;
			font-weight: 600;
			line-height: 56rpx;
			color: #2c3e50;
			letter-spacing: 0.5rpx;
		}
		
		// 作者和日期元信息
		.article-meta {
			padding: 0 30rpx 20rpx;
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #999;
			
			.author-name {
				color: #666;
			}
			
			.meta-dot {
				margin: 0 10rpx;
				color: #ddd;
			}
			
			.publish-date {
				color: #999;
			}
		}
		
		// 标签区域
		.article-tags {
			padding: 0 30rpx 25rpx;
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;
			
			.tag-item {
				padding: 8rpx 24rpx;
				font-size: 24rpx;
				color: #1890ff;
				background-color: transparent;
				border: 2rpx solid #1890ff;
				border-radius: 30rpx;
				display: inline-block;
			}
		}
		
		// 封面图片
		.article-cover {
			width: 100%;
			margin-bottom: 30rpx;
			
			.cover-image {
				width: 100%;
				height: 400rpx;
				display: block;
			}
		}
		
		// 文章内容
		.article-content {
			padding: 0 30rpx 30rpx;
			font-size: 30rpx;
			line-height: 50rpx;
			color: #555;
			text-align: justify;
			letter-spacing: 0.5rpx;
		}
		
		// 互动操作栏
		.article-actions {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 25rpx 30rpx;
			border-top: 1px solid #f0f0f0;
			border-bottom: 1px solid #f0f0f0;
			margin: 20rpx 0;
			
			.action-left,
			.action-right {
				display: flex;
				align-items: center;
				gap: 30rpx;
			}
			
			.action-btn {
				display: flex;
				align-items: center;
				gap: 8rpx;
				padding: 10rpx;
				cursor: pointer;
				
				.action-text {
					font-size: 26rpx;
					color: #666;
				}
				
				&:active {
					opacity: 0.6;
				}
			}
		}
		
		// 评论区域
		.comments-section {
			padding: 30rpx;
			
			.comments-header {
				display: flex;
				align-items: baseline;
				margin-bottom: 30rpx;
				
				.comments-title {
					font-size: 34rpx;
					font-weight: 600;
					color: #2c3e50;
				}
				
				.comments-count {
					margin-left: 10rpx;
					font-size: 26rpx;
					color: #999;
				}
			}
			
			.comment-list {
				.empty-comment {
					padding: 80rpx 0;
					text-align: center;
					font-size: 28rpx;
					color: #bbb;
				}
				
				.comment-item {
					display: flex;
					margin-bottom: 30rpx;
					padding-bottom: 30rpx;
					border-bottom: 1px solid #f5f5f5;
					
					&:last-child {
						border-bottom: none;
						padding-bottom: 0;
						margin-bottom: 0;
					}
					
					.comment-avatar {
						width: 60rpx;
						height: 60rpx;
						border-radius: 50%;
						overflow: hidden;
						background-color: #f0f0f0;
						margin-right: 20rpx;
						flex-shrink: 0;
						
						image {
							width: 100%;
							height: 100%;
						}
					}
					
					.comment-body {
						flex: 1;
						
						.comment-user-info {
							display: flex;
							align-items: center;
							justify-content: space-between;
							margin-bottom: 10rpx;
							
							.comment-username {
								font-size: 26rpx;
								font-weight: 500;
								color: #333;
							}
							
							.comment-time {
								font-size: 22rpx;
								color: #aaa;
							}
						}
						
						.comment-text {
							font-size: 28rpx;
							line-height: 42rpx;
							color: #555;
							word-break: break-all;
						}
					}
				}
			}
		}
	}
	
	// 底部评论输入框
	.comment-input-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		background-color: #ffffff;
		border-top: 1px solid #e8e8e8;
		z-index: 1000;
		
		.comment-input {
			flex: 1;
			height: 70rpx;
			padding: 0 24rpx;
			background-color: #f5f5f5;
			border-radius: 35rpx;
			font-size: 28rpx;
			border: 1px solid #e8e8e8;
		}
		
		.send-btn {
			margin-left: 20rpx;
			width: 70rpx;
			height: 70rpx;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: #ffffff;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0;
			border: none;
			
			&[disabled] {
				background: #ddd;
				opacity: 0.6;
			}
			
			&:active:not([disabled]) {
				opacity: 0.8;
			}
		}
	}
}
</style>
